import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult.vue'
// import ArticleDetail from '@/views/ArticelDetail'
// import UserEdit from '@/views/User/UserEdit.vue'
// import Chat from '@/views/Chat'
import { getToken } from '@/utils/token'
// 总结:
// 路由懒加载: 为了让第一个页面, 加载的app.js小一点, 打开网页快一点
// 思路: 把组件对应js, 分成若干个.js, 路由切换到哪个页面, 才去加载对应的.js文件
// 原因: webpack分析入口时, 发现router里上来就import所有页面, 所以直接打包进app.js->很大
// 解决: 当路由路径匹配规则时, 才现去import引入对应的组件js文件
// webpackChunName注释语法, 给生成的js文件起名字

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/layout/home'
},
{
  path: '/login',
  component: () => import(/* webpackChunkName: "Login" */ '@/views/Login'),
  beforeEnter: (to, from, next) => {
    if (getToken()?.length > 0 && to.path === '/login') {
      // 证明有token-已经登录了
      next(false) // 阻止跳转原地呆着
    } else {
      next()
    }
  }
}, {
  path: '/layout',
  component: () => import(/* webpackChunkName: "Layout" */ '@/views/Layout'),
  children: [{
    path: 'home',
    component: () => import(/* webpackChunkName: "Home" */ '@/views/Home')
  }, {
    path: 'user',
    component: () => import(/* webpackChunkName: "User" */ '@/views/User')
  }]
},
{
  path: '/search',
  component: () => import(/* webpackChunkName: "Search" */ '@/views/Search')
},
{ // 搜索结果
  path: '/search_result/:kw',
  component: () => import(/* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult.vue')
},
{ // 文章详情
  path: '/detail',
  component: () => import(/* webpackChunkName: "ArticelDetail" */ '@/views/ArticelDetail')
},
{ // 用户资料
  path: '/user_edit',
  component: () => import(/* webpackChunkName: "UserEdit" */ '@/views/User/UserEdit.vue')
},
{ // 客服聊天
  path: '/chat',
  component: () => import(/* webpackChunkName: "Chat" */ '@/views/Chat')
}
]

const router = new VueRouter({
  routes
})

// router.beforeEach((to, from, next) => {
//   // 有token, 不能去登录页
//   // 无token, 需要用户"权限"的才需要去登录页
//   if (getToken()?.length > 0 && to.path === '/login') {
//     // 证明有token-已经登录了
//     next(false) // 阻止跳转原地呆着
//   } else {
//     next()
//   }
// })

export default router
